from fastapi import APIRouter, Depends
from typing import Dict, Any
from src.containers import get_knowledge_base_service, get_knowledge_graph_service
from sqlalchemy import text

router = APIRouter(prefix="/health", tags=["health"])

@router.get("/knowledge-base")
async def check_knowledge_base_health():
    """检查知识库服务健康状态"""
    try:
        kb_service = get_knowledge_base_service()
        
        # 检查数据库连接
        db = kb_service.SessionLocal()
        db.execute(text("SELECT 1"))
        db.close()
        
        # 检查向量索引
        index_status = "available" if kb_service.vector_index else "unavailable"
        index_size = kb_service.vector_index.ntotal if kb_service.vector_index else 0
        
        # 检查嵌入模型
        model_status = "available" if kb_service.embedding_model else "unavailable"
        
        return {
            "status": "healthy",
            "database": "connected",
            "vector_index": {
                "status": index_status,
                "size": index_size
            },
            "embedding_model": model_status
        }
    except Exception as e:
        return {
            "status": "unhealthy",
            "error": str(e)
        }

@router.get("/knowledge-graph")
async def check_knowledge_graph_health():
    """检查知识图谱服务健康状态"""
    try:
        kg_service = get_knowledge_graph_service()
        
        # 检查图数据库连接
        if kg_service.graph:
            kg_service.graph.run("MATCH (n) RETURN count(n) AS count").data()
            db_status = "connected"
        else:
            db_status = "disconnected"
        
        # 检查向量索引
        index_status = "available" if kg_service.vector_index else "unavailable"
        index_size = kg_service.vector_index.ntotal if kg_service.vector_index else 0
        
        # 检查嵌入模型
        model_status = "available" if kg_service.embedding_model else "unavailable"
        
        return {
            "status": "healthy",
            "graph_database": db_status,
            "vector_index": {
                "status": index_status,
                "size": index_size
            },
            "embedding_model": model_status
        }
    except Exception as e:
        return {
            "status": "unhealthy",
            "error": str(e)
        }

@router.get("/")
async def check_overall_health():
    """检查整体健康状态"""
    kb_health = await check_knowledge_base_health()
    kg_health = await check_knowledge_graph_health()
    
    overall_status = "healthy" if (
        kb_health["status"] == "healthy" and 
        kg_health["status"] == "healthy"
    ) else "unhealthy"
    
    return {
        "status": overall_status,
        "knowledge_base": kb_health,
        "knowledge_graph": kg_health
    }
